package com.motu.monstercity.server.game.logic;

import com.motu.monstercity.module.common.iap.Iap;
import com.motu.monstercity.module.common.iap.IapGift;
import com.motu.monstercity.module.common.redis.RedisKey;
import com.motu.monstercity.module.common.servermanager.ServerManager;
import com.motu.monstercity.module.common.utility.Constant;
import com.motu.monstercity.protocol.Common;
import com.motu.monstercity.protocol.Common.PBUserData;
import com.motu.monstercity.protocol.CsGameSystem;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.CommonUtils;
import com.motu.monstercity.server.game.base.LockKey;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.bag.ItemId;
import com.motu.monstercity.server.game.commondata.iap.PrivilegeCardConstant;
import com.motu.monstercity.server.game.commondata.mail.MailConstant;
import com.motu.monstercity.server.game.commondata.rank.RankConstant;
import com.motu.monstercity.server.game.commondata.shop.Shop;
import com.motu.monstercity.server.game.commondata.skill.Skill;
import com.motu.monstercity.server.game.commondata.system.SystemConstant;
import com.motu.monstercity.server.game.commondata.union.*;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.main.MainService;
import com.motu.vertx.module.utility.model.EntityManager;
import com.motu.vertx.module.utility.redis.RedisTools;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.Future;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.shareddata.Lock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

public class UnionManager extends UnionUserData {
    private static final Logger logger = LoggerFactory.getLogger(UnionManager.class);

    public static final int POST_TYPE_MASTER = 1; // 盟主
    public static final int POST_TYPE_DEPUTY  = 2; // 副盟主
    public static final int POST_TYPE_ELITE = 3; // 精英
    public static final int POST_TYPE_COMMON = 0; // 成员
    public static final byte NO = 0;
    public static final byte YES = 1;

    // 初始化 下发联盟模块的用户数据
    public static void loadInitUnionUserData(PBUserData.Builder pbUserData, UserInfo userInfo) {
        long userId = userInfo.getId();
        UserUnion userUnion = getUserUnion(userId);
        ProtoDataUtils.updatePBUserData(pbUserData, userUnion, true);
        if (userUnion.getUnionId() > 0) {
            UnionInfo unionInfo = getUnionInfo(userUnion.getUnionId());
            ProtoDataUtils.updatePBUserData(pbUserData, unionInfo, true);
            pbUserData.getUnionBuilder().getUnionReciprocityInfoBuilder().setCanHelpNum(countHelpNum(userId, userUnion.getUnionId(), unionInfo)); // 获取联盟可帮助人数

            UserUnionReciprocity userUnionReciprocity = getUserUnionReciprocity(userId);// 联盟互助今日已经获得的联盟币数量
            ProtoDataUtils.updatePBUserData(pbUserData, userUnionReciprocity);

            //下发建筑模块
            List<UnionBuild> unionBuildList = UnionManager.getUnionBuildList(unionInfo.getId());
            for (UnionBuild unionBuild : unionBuildList) {
                ProtoDataUtils.updatePBUserData(pbUserData, unionBuild,true);//下发建筑信息
            }
        }
    }

    /**
     * 更新联盟总收益-加锁
     * @param userInfo
     * @param addEar
     */
    public static void updateUnionEarnRankByLock (UserInfo userInfo,long addEarn){
        long userId = userInfo.getId();
        UserUnion userUnion = getUserUnion(userId);
        long unionId = userUnion.getUnionId();
        if (unionId != 0){
            Lock lock = null;
            try {
                lock = MainService.getVertLock(LockKey.getUnionInfoLock(unionId));
                updateUnionEarnRank(userInfo.getServerId(),unionId,addEarn);
            } catch (Exception e) {
                logger.error("updateUnionEarnRank userId :" +userId+" error :" + Tool.getException(e));
            } finally {
                MainService.releaseVertLock(lock);
            }

        }
    }

    /**
     * 更新联盟总收益--不加锁
     * @param serverId
     * @param unionId
     * @param addEarn
     */
    public static void updateUnionEarnRank (int serverId,long unionId,long addEarn){
        logger.info("updateUnionEarnRankByLock unionId :" +unionId + " addEarn:" + addEarn);
        UnionInfo unionInfo = getUnionInfo(unionId);
        unionInfo.addPower(addEarn);
        unionInfo.update();
        long totalEaen = unionInfo.getPower();
        //更新本服排行榜
        RankManager.updateRank(RankConstant.SERVER_RANK_UNION_EARN, serverId, unionId, totalEaen, "0");
        //更新跨服排行榜
        int serverGroup = ServerManager.getWarZoneId(serverId);
        RankManager.updateRank(RankConstant.CROSS_RANK_UNION, serverGroup, unionId, totalEaen, "0");
    }

    /**
     * 检测联盟红点
     * @param builder
     * @param userInfo
     * @return
     */
    public static boolean checkRedPoint(UserInfo userInfo,CsGameSystem.CSGameSystemRedPointResponse.Builder builder){
        boolean hasRedPoint = false;
        CsGameSystem.RedPoint_Union.Builder redPoint = builder.getUnionBuilder();
        long userId = userInfo.getId();
        UserUnion userUnion = getUserUnion(userId);
        if (userUnion.getUnionId() != 0 ) {
            long unionId = userUnion.getUnionId();
            UnionInfo unionInfo = getUnionInfo(unionId);
            if (unionInfo != null) {
                //初级捐献是否还有次数
                int donateType = UnionDonateMain.TYPE_1;//初级捐献
                JsonObject userDonateJson = userUnion.getUserDonateJson();
                UnionDonateMain unionDonateMain = UnionManager.getUnionDonateMain(donateType);
                int donateNum = userDonateJson.containsKey(String.valueOf(donateType)) ? userDonateJson.getInteger(String.valueOf(donateType)) : 0;
                if (donateNum < unionDonateMain.getNum()) {
                    hasRedPoint = true;
                    redPoint.setDonate(true);
                }
                //是否可领取捐献进度奖励
                UnionDonateInfo unionDonateInfo = UnionManager.getUnionDonateInfo(unionId);
                if (unionDonateInfo != null) {
                    ConcurrentHashMap<Integer, UnionDonateDay> unionDonateDayMap = getUnionDonateDayMap();
                    List<Integer> userDonateProgressRewardList = userUnion.getUserDonateProgressReward();
                    for (UnionDonateDay unionDonateDay : unionDonateDayMap.values()) {
                        int progress = unionDonateDay.getNum();
                        if (userDonateProgressRewardList.indexOf(progress) == -1 && unionDonateInfo.getProgress() >= unionDonateDay.getNum()) {
                            hasRedPoint = true;
                            redPoint.setDonate(true);
                        }
                    }
                }
                //联盟建筑是否可建造/升级
                ConcurrentHashMap<Integer, UnionBuildMain> unionBuildMainMap = getUnionBuildMainMap();
                for (UnionBuildMain unionBuildMain : unionBuildMainMap.values()) {
                    if (unionBuildMain.getUnlockLevel() <= unionInfo.getLevel()) {
                        int buildId = unionBuildMain.getId();
                        UnionBuild unionBuild = UnionManager.getUnionBuild(unionId,buildId);
                        //判断是否可建造
                        if(unionBuild == null ){
                            if (userUnion.IsPostElite()) {
                                hasRedPoint = true;
                                redPoint.setBuild(true);
                            }
                        }else {
                            //建筑建造完 判断是否足够单次升级
                            if( unionBuild.getBuildTime() < TimeUtils.getCurTime()){
                                if (BagManager.checkNeedItemNum(userInfo, ItemId.TYPE_UNION_BUILD , AllParam.UNION_BUILD_LEVELUP_NEED_NUM)) {
                                    hasRedPoint = true;
                                    redPoint.setBuild(true);
                                }
                            }
                        }
                    }
                }
                // 联盟大礼是否有红点
                if (isHaveUnionGiftRed(unionId, userId,  redPoint, unionInfo)){
                    hasRedPoint = true;
                }
                // 联盟互助
                List<UserUnionReciprocityRecord> records = UnionManager.getUserUnionReciprocityRecordList(userId);// 帮助记录
                int count = 0;
                for (UnionReciprocityList unionReciprocityList : UnionManager.getUnionReciprocityList(unionId)) {
                    if (unionReciprocityList.isCanHelp(userId, records, unionInfo)) {
                        count++;
                    }
                }
                if (count > 0) {
                    hasRedPoint = true;
                    redPoint.setHelp(count);
                }

                //判断折扣商店
                int discountShopPrice = userUnion.getDiscountShopPrice();
                if (discountShopPrice == 0) {
                    //未砍价
                    redPoint.setDiscountShop(true);
                    hasRedPoint = true;
                }
//                if (userUnion.getIsDiscountShopBuy() == 0) {
//                    //未购买
//                    redPoint.setDiscountShop(true);
//                    hasRedPoint = true;
//                }

            }
        }
        return hasRedPoint;
    }


    // 联盟大礼的红点
    public static boolean isHaveUnionGiftRed(long unionId, long userId, CsGameSystem.RedPoint_Union.Builder redPoint, UnionInfo unionInfo) {
        // 联盟宝箱
        boolean hasRedPoint = false;
        UnionBuild unionBuild = UnionManager.getUnionBuild(unionId,UnionBuildMain.BUILD_ID_MAIN);
        if (unionBuild != null && unionBuild.getBuildTime() < TimeUtils.getCurTime()) {
            // 获取大宝箱进度的红点
            UnionBoxInfo unionBoxInfo = UnionManager.getUnionBoxInfo(unionId);
            if (unionBoxInfo != null) {
                UserUnionBox userUnionBox = UnionManager.getUserUnionBox(userId);
                if (userUnionBox != null) {
                    int totalNum = unionBoxInfo.getTotalNum();
                    int receiveBoxNum = userUnionBox.getReceiveBoxNum();
                    if (receiveBoxNum < totalNum) {     // 有大宝箱奖励可领取
                        redPoint.setBigBox(Math.max(0,totalNum - receiveBoxNum));
                    }
                }
            }
            List<UnionGiftBoxList> unionGiftBoxListList = UnionManager.getUnionGiftBoxList(unionId);
            if (!unionGiftBoxListList.isEmpty()) { // 没有礼盒
                for (int boxType : UnionConstant.UNION_GIFT_BOX_TYPES) {
                    List<Long> receiveGiftBoxRecordIds = UnionManager.getReceiveGiftBoxRecordIds(unionId, userId);
                    List<UnionGiftBoxList> takeList = unionGiftBoxListList.stream()
                            .filter(x -> x.getType() == boxType && x.getUserId() != userId && !receiveGiftBoxRecordIds.contains(x.getId())).toList();
                    if (takeList.isEmpty()) {
                        continue;
                    }

                    if (boxType == UnionConstant.UNION_GIFT_BOX_TYPE_1) {
                        UserUnionBox userUnionBox = UnionManager.getUserUnionBox(userId);
                        if (userUnionBox == null) {
                            if (unionBoxInfo == null) { // 兼容以前旧联盟数据（TODO 待删除）
                                unionBoxInfo = new UnionBoxInfo(unionId, unionInfo.getLevel());
                                unionBoxInfo.insert();
                            }
                            userUnionBox = new UserUnionBox(userId, unionBoxInfo.getBoxId(), unionBoxInfo.getTotalNum());
                            userUnionBox.insert();
                        }
                        //计算可使用次数
                        UnionBuildUpgrade unionBuildUpgrade = UnionManager.getUnionBuildUpgrade(UnionBuildMain.BUILD_ID_BUSINESS, unionBuild.getLevel());
                        int buildUpgradeNum = unionBuildUpgrade.getEffectTypeValue(UnionBuildUpgrade.EFFECT_TYPE_MAIN);//建筑等级额外次数
                        int maxNum = AllParam.UNION_ACTIVE_GIFT_BOX_DAILY_RECEIVE_MAX + buildUpgradeNum;
                        int receiveMaxNum = maxNum - userUnionBox.getReceiveActiveBoxNum();
                        if (receiveMaxNum > 0) { // 超过领取上限了
                            hasRedPoint = true;
                            receiveMaxNum = Math.min(receiveMaxNum, takeList.size());
                            redPoint.putBoxes(boxType, receiveMaxNum);
                        }
                    } else {
                        hasRedPoint = true;
                        redPoint.putBoxes(boxType, takeList.size());
                    }
                }
            }
        }
        return hasRedPoint;
    }


    // 发送联盟大礼红点
    public static void sendUnionGiftRedPoint( UnionInfo unionInfo) {
        if (unionInfo == null) {return;}
        long unionId = unionInfo.getId();
        JsonArray memberIds = UnionManager.getUnionMemberIdList(unionId);
        for (int i = 0; i < memberIds.size(); i++) {
            long memberId = Long.parseLong(memberIds.getString(i));
            UserInfo memberInfo = GameUser.getUserInfo(memberId);
            if (memberInfo != null) {
                GameUser.sendRedPointPrompt(memberInfo, null, SystemConstant.RED_POINT_UNION_BOX,unionInfo);
            }
        }
    }


    /**
     * 构建联盟玩家展示数据
     * @param userUnion
     * @return
     */
    public static Common.PBUserUnionMember.Builder takeUserUnionMemberBuilder(UserUnion userUnion) {
        long userId = userUnion.getId();
        Common.PBUserUnionMember.Builder sb = Common.PBUserUnionMember.newBuilder();
        sb.setUserId(userId);
        if (userUnion.getUnionId() != 0) {
            sb.setPost(userUnion.getPost());
            sb.setContribution(userUnion.getContribution());
            sb.setDayContribution(userUnion.getDayContribution());
        }

        UserShow userShow = GameUser.getUserShow(userId);
        sb.setUserShow(userShow.takeInitBuilder());

        //离线时间
        boolean isConnect = GameUser.isConnect(userId);
        if (!isConnect) {
            UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
            sb.setOfflineTime(userExtInfo.getOfflineTime());
        }

        return sb;
    }

    public static Common.PBUserUnionMember.Builder takeUserUnionMemberBuilder(long userId) {
        UserUnion userUnion = getUserUnion(userId);
        return takeUserUnionMemberBuilder(userUnion);
    }

    /**
     * 获取联盟成员列表并排序
     * @param unionId
     * @return
     */
    public static List<Common.PBUserUnionMember>  sortUnionMemberList(long unionId) {
        List<UnionMember> unionMemberList = UnionManager.getUnionMemberList(unionId);
        return sortUnionMemberList(unionMemberList);
    }

    /**
     * 获取联盟成员列表并排序-暂不处理,客户端处理排序
     * @param unionMemberList
     * @return
     */
    public static List<Common.PBUserUnionMember>  sortUnionMemberList(List<UnionMember> unionMemberList) {
        List<Common.PBUserUnionMember> pbUnionMemberList = new ArrayList<>();
        for (UnionMember unionMember : unionMemberList) {
            try {
                UserUnion userUnionMember = UnionManager.getUserUnion(unionMember.getUserId());
                pbUnionMemberList.add(UnionManager.takeUserUnionMemberBuilder(userUnionMember).build());
            } catch (Exception e) {
                String errMsg = Tool.getException(e);
                MainService.logger.error(errMsg);
            }
        }
        return pbUnionMemberList;
    }

    /**
     * 删除玩家所有联盟申请记录
     * @param userId
     */
    public static void deleteAllUserApply(long userId) {
        List<UserUnionApply>  userUnionApplyList = UnionManager.getUserUnionApplyList(userId);
        for (UserUnionApply userUnionApply : userUnionApplyList) {
            deleteUserAndUnionApply(userUnionApply.getUserId(),userUnionApply.getUnionId(),null,userUnionApply);
        }
    }

    /**
     * 删除联盟所有申请记录
     * @param unionId
     */
    public static void deleteAllUnionApply(long unionId) {
        List<UnionUserApply>  unionUserApplyList = UnionManager.getUnionUserApplyList(unionId);
        for (UnionUserApply unionUserApply : unionUserApplyList) {
            deleteUserAndUnionApply(unionUserApply.getUserId(),unionUserApply.getUnioinId(),unionUserApply,null);
        }
    }

    /**
     * 删除该玩家和该联盟的对应申请记录
     * @param userId
     * @param unionId
     */
    public static void deleteUserAndUnionApply(long userId, long unionId,UnionUserApply unionUserApply,UserUnionApply userUnionApply) {
        unionUserApply =  unionUserApply != null ? unionUserApply : UnionManager.getUnionUserApply(unionId, userId);
        if (unionUserApply != null) {
            unionUserApply.delete();
        }

        userUnionApply = userUnionApply != null ? userUnionApply : UnionManager.getUserUnionApply(userId,unionId);
        if (userUnionApply != null) {
            userUnionApply.delete();
        }
    }

    /**
     * 构建联盟用户记录对象
     * @param userId
     * @param value
     * @param totalValue
     * @param type
     * @return
     */
    public static Common.PBUnionUserRecord.Builder takePBUnionUserRecordBuilder(long userId,int value,int totalValue,int type) {
        Common.PBUnionUserRecord.Builder  pbUnionUserRecordBuilder = Common.PBUnionUserRecord.newBuilder();
        pbUnionUserRecordBuilder.setUserId(userId);
        pbUnionUserRecordBuilder.setType(type);
        pbUnionUserRecordBuilder.setValue(value);
        pbUnionUserRecordBuilder.setTotalValue(totalValue);
        UserShow userShow = GameUser.getUserShow(userId);
        pbUnionUserRecordBuilder.setUserShow(userShow.takeInitBuilder());
        return pbUnionUserRecordBuilder;
    }

    /**
     * 获取联盟活动充值时间
     * @return
     */
    public static JsonArray getUnionActChargeTime() {
        if(AllParam.UNION_ACY_CHARGE_START_TIME == "" || AllParam.UNION_ACY_CHARGE_END_TIME == ""){
            return new JsonArray();
        }
        String[] startTimeArray  = AllParam.UNION_ACY_CHARGE_START_TIME.split(";");
        String[] endTimeArray  = AllParam.UNION_ACY_CHARGE_END_TIME.split(";");
        long startTime = TimeUtils.getWeekOneTime(Integer.parseInt(startTimeArray[0]),startTimeArray[1]);
        long endTime = TimeUtils.getWeekOneTime(Integer.parseInt(endTimeArray[0]),endTimeArray[1]) + TimeUtils.DAY;
        JsonArray result = new JsonArray();
        result.add(startTime);
        result.add(endTime);
        return result;
    };

    /**
     * 联盟限时充值活动 回调事件
     * @param userInfo
     * @param iapGift
     * @param iap
     * @param pbUserData
     */
    public static void updateUnionActCharge(UserInfo userInfo, IapGift iapGift, Iap iap, PBUserData.Builder pbUserData) {
        long userId = userInfo.getId();
        UserUnion userUnion = getUserUnion(userId);
        if (userUnion.getUnionId() == 0 ) {
            return;//没有联盟
        }
        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = getUnionInfo(userUnion.getUnionId());
        if (unionInfo == null) {
            return ;//联盟不存在
        }
        //判断活动时间
        JsonArray actChargeTimeArray = getUnionActChargeTime();
        if (actChargeTimeArray.size() == 0){
            return;//活动时间未设置,暂不开放活动
        }
        String startDayStr = TimeUtils.getDayStr(actChargeTimeArray.getLong(0));
        long startTime = actChargeTimeArray.getLong(0);
        long endTime = actChargeTimeArray.getLong(1);
        long curTime = TimeUtils.getCurTime();
        if (curTime > startTime && curTime < endTime) {
            double vipSocre = iap.getScore();
            //首次充值才会记录
            if(userUnion.getActChargePrice() == 0) {
                UnionActChargeInfo unionActChargeInfo = UnionManager.getUnionActChargeInfo(unionId);
                if (unionActChargeInfo == null) {
                    unionActChargeInfo = new UnionActChargeInfo(unionId,startTime);
                    unionActChargeInfo.insert();
                }else {
                    unionActChargeInfo.addNum(1);
                    unionActChargeInfo.update();
                }
                ProtoDataUtils.updatePBUserData(pbUserData, unionActChargeInfo);
                String unionActChargeRecordRediskey = RedisKey.getUnionActChargeRecordKey(unionId,startDayStr);
                boolean isExists = Future.await(RedisTools.exists(unionActChargeRecordRediskey));
                RedisTools.addRank(unionActChargeRecordRediskey, userId, vipSocre);
                if (!isExists) {
                    RedisTools.expire(unionActChargeRecordRediskey, 5 * TimeUtils.DAY);//保留5天联盟充值记录
                }
                userUnion.addActChargePrice((int) vipSocre);//记录vip积分
                userUnion.update();
            }
        }
    }

    /**
     * 是否可在商店购买宝箱
     * 1. 活动期间
     * @param userInfo
     * @param Shop
     * @return
     */
    public static boolean isShopBuyBox(UserInfo userInfo, Shop shop){
        long userId = userInfo.getId();
        UserUnion userUnion = getUserUnion(userId);
        long unionId = userUnion.getUnionId();
        if (unionId == 0) {
            return false;//没有联盟不可购买
        }
        UnionBuild unionBuild = getUnionBuild(unionId, UnionBuildMain.BUILD_ID_SHOP);
        if (unionBuild == null || unionBuild.getBuildTime() > TimeUtils.getCurTime()) {
            return false;//建筑未建造完成
        }
        if (shop.getUnlockValue() > unionBuild.getLevel()) {
            return false;//等级不达标,商店未开放
        }
        return true;
    }

    private static final String SHORT_NAME_PATTERN = "[a-zA-Z0-9]+";
    public static boolean checkShortName(String shortName) {
        return shortName.matches(SHORT_NAME_PATTERN);
    }


    // 过滤已领取且过期的
    public static JsonArray getReceiveGiftBoxReward(long unionId, JsonArray receiveGiftBoxRecordArray) {
        JsonArray newReceiveGiftBoxRecordArray = new JsonArray();
        List<Long> allGiftBoxIds = getUnionGiftBoxIdList(unionId);
        for (int i = 0; i < receiveGiftBoxRecordArray.size(); i++) {
            if (Tool.isInList(allGiftBoxIds, receiveGiftBoxRecordArray.getLong(i))) {//  未过期且已领取，重新保存
                newReceiveGiftBoxRecordArray.add(receiveGiftBoxRecordArray.getLong(i));
            }
        }
        return newReceiveGiftBoxRecordArray;
    }

    // 获取领取礼盒记录列表ID
    public static List<Long> getReceiveGiftBoxRecordIds(long unionId, long userId) {
        List<Long> result = new ArrayList<>();
        List<UserUnionGiftBoxRecord> recordList = getUserUnionGiftBoxRecordList(userId);
        for (UserUnionGiftBoxRecord record : recordList) {
            result.add(record.getGiftBoxId());
        }
        return result;
    }

    // 获取宝箱的最大进度
    public static int getUnionBoxMaxProgress(int unionLevel) {
        int maxProgress = 0;
        ConcurrentHashMap<Integer, UnionBoxReward> unionBoxRewardMap = getUnionBoxRewardMap();
        for (Map.Entry<Integer, UnionBoxReward> entry : unionBoxRewardMap.entrySet()) {
            UnionBoxReward unionBoxReward = entry.getValue();
            if (unionLevel < unionBoxReward.getUnionLevel()) {
                break;
            }
            maxProgress = unionBoxReward.getProgress();
        }

        return maxProgress;
    }

    // 获取当前宝箱ID
    public static int getUnionBoxCurrentBoxId(int unionLevel) {
        int boxId = 0;
        ConcurrentHashMap<Integer, UnionBoxReward> unionBoxRewardMap = getUnionBoxRewardMap();
        for (Map.Entry<Integer, UnionBoxReward> entry : unionBoxRewardMap.entrySet()) {
            UnionBoxReward unionBoxReward = entry.getValue();
            if (unionLevel < unionBoxReward.getUnionLevel()) {
                break;
            }
            boxId = unionBoxReward.getId();
        }

        return boxId;
    }

    // 根据数量获取某阶段的宝箱奖励
    public static void getUnionBoxRewardByNun(int boxId, int num, List<RewardItem> takeRewardList) {
        if (num <= 0) {
            return ;
        }
        UnionBoxReward unionBoxReward = UnionUserData.getUnionBoxReward(boxId);
        if (unionBoxReward == null) {
            return ;
        }
        List<RewardItem> rewardItemList = CommonUtils.takeReawrdItemFromStr(unionBoxReward.getReward());
        CommonUtils.multipleItemList(rewardItemList, num);
        takeRewardList.addAll(rewardItemList);
    }

    // 更新宝箱信息
    public static void updateUnionBoxInfo(long unionId, int unionLevel){
        int boxId = getUnionBoxCurrentBoxId(unionLevel);
        UnionBoxInfo  unionBoxInfo = UnionManager.getUnionBoxInfo(unionId);
        if (boxId > 0 && boxId != unionBoxInfo.getBoxId()) {
            JsonArray boxNumRecordArray = unionBoxInfo.getBoxNumRecordArray();
            boxNumRecordArray.add(unionBoxInfo.getBoxId());
            boxNumRecordArray.add(unionBoxInfo.getTotalNum());
            unionBoxInfo.putBoxId(boxId);
            unionBoxInfo.putBoxNumRecord(boxNumRecordArray.toString());
            unionBoxInfo.update();
        }
    }

    // 插入领取礼盒记录
    public static  void insertUserUnionGiftBoxRecord(long userId, UnionGiftBoxList unionGiftBoxList) {
        UserUnionGiftBoxRecord userUnionGiftBoxRecord = new UserUnionGiftBoxRecord(userId, unionGiftBoxList.getId(), unionGiftBoxList.getActivateTime());
        userUnionGiftBoxRecord.doCreate();
    }


    // 添加礼盒列表（0活跃礼盒-每日任务； 1联盟赠礼-购买联盟礼包）
    public static void addUnionGiftBoxList(UserInfo userInfo,int itemId, long itemNum, int type, String param) {
        UserUnion userUnion = UnionManager.getUserUnion(userInfo.getId());
        if (userUnion != null) {
            long unionId = userUnion.getUnionId();
            UnionInfo unionInfo = UnionManager.getUnionInfo(unionId);
            if (unionInfo != null) {
                for (int i = 0; i < itemNum; i++) { // 宝箱类型=4;且为自动打开得才算
                    // 每个宝箱都要生成联盟记录
                    UnionGiftBoxList unionGiftBoxList = new UnionGiftBoxList(unionId, userInfo.getId(), type, CommonUtils.getRewardString(itemId, 1), param);
                    unionGiftBoxList.doCreate();
                }
                UnionManager.sendUnionGiftRedPoint(unionInfo); // 发送联盟红点
            }
        }
    }

    /**
     * 处理玩家联盟宝箱信息，离开联盟时
     * 1. 删除用户联盟宝箱记录
     * 2. 删除用户联盟礼盒领取记录
     * 5. 发放未领取的联盟赠礼（type = 2）奖励邮件
     * @param userInfo
     * @param unionId
     */
    public static void dealUnionBoxInfoByLeave(UserInfo userInfo, long unionId) {
        long userId = userInfo.getId();
        // 删除用户联盟宝箱数据
        UserUnionBox userUnionBox = getUserUnionBox(userId);
        List<RewardItem> takeRewardList = new ArrayList<>();
        if (userUnionBox != null) {
            // 补发未领取礼盒的奖励
            UnionBoxInfo unionBoxInfo = UnionManager.getUnionBoxInfo(unionId);
            int totalNum = unionBoxInfo.getTotalNum();
            int receiveBoxNum = userUnionBox.getReceiveBoxNum();
            if (totalNum > receiveBoxNum) {
                if (unionBoxInfo.getBoxId() > userUnionBox.getReceiveBoxId()) { // 先补发未领取的跨阶段奖励
                    JsonArray boxNumRecordArray = unionBoxInfo.getBoxNumRecordArray();
                    for (int i = 0; i < boxNumRecordArray.size(); i++) {
                        if (i % 2 == 0) {
                            int boxId = boxNumRecordArray.getInteger(i);
                            int oldNum = boxNumRecordArray.getInteger(i + 1);
                            if (receiveBoxNum >= oldNum){
                                continue;
                            }
                            int receiveNum = oldNum - receiveBoxNum;
                            getUnionBoxRewardByNun(boxId, receiveNum, takeRewardList);
                            receiveBoxNum = oldNum;
                        }
                    }
                }
                int receiveNum = totalNum - receiveBoxNum;
                getUnionBoxRewardByNun(unionBoxInfo.getBoxId(), receiveNum, takeRewardList);

            }
            userUnionBox.delete();
        }

        // 删除用户联盟礼盒领取记录
        List<Long> receiveGiftBoxRecordIds =  new ArrayList<>();
        List<UserUnionGiftBoxRecord> recordList = getUserUnionGiftBoxRecordList(userId);
        for (UserUnionGiftBoxRecord userUnionGiftBoxRecord : recordList) {
            receiveGiftBoxRecordIds.add(userUnionGiftBoxRecord.getGiftBoxId());
            userUnionGiftBoxRecord.delete();
        }


        // 领取联盟赠礼的奖励（活跃礼箱不需要领取）
        List<UnionGiftBoxList> unionGiftBoxListList = getUnionGiftBoxList(unionId);
        if (!unionGiftBoxListList.isEmpty()) {
            List<UnionGiftBoxList> takeList = unionGiftBoxListList.stream().filter(x -> x.getType() == 2 && x.getUserId() != userId && !receiveGiftBoxRecordIds.contains(x.getId())).toList();
            // 发放未领取的联盟赠礼（type = 2）奖励邮件
            for (UnionGiftBoxList unionGiftBoxList : takeList) {
                takeRewardList.addAll(CommonUtils.takeReawrdItemFromStr(unionGiftBoxList.getReward()));
            }
        }

        if (!takeRewardList.isEmpty()) {
            MailManager.sendSystemMail(userId, MailConstant.UNION_GIFT_BOX_REWARD_TITLE, MailConstant.UNION_GIFT_BOX_REWARD_CONTENT, takeRewardList, LogType.UNION_DISPOSABLE_BOX_PROGRESS_REWARD);
        }

    }

    /**
     * 构建联盟宝箱列表协议信息
     * @param unionGiftBoxList
     * @return
     */
    public static Common.PBUnionGiftBoxList.Builder takePBUnionGiftBoxListBuilder(UnionGiftBoxList unionGiftBoxList) {
        Common.PBUnionGiftBoxList.Builder builder = Common.PBUnionGiftBoxList.newBuilder();
        builder.setId(unionGiftBoxList.getId());
        builder.setType(unionGiftBoxList.getType());
        builder.setActivateTime(unionGiftBoxList.getActivateTime());
        builder.setReward(unionGiftBoxList.getReward());
        builder.setParam(unionGiftBoxList.getParam());

        UserShow userShow = GameUser.getUserShow(unionGiftBoxList.getUserId());
        builder.setUserShow(userShow.takeInitBuilder());
        return builder;
    }


    /**
     * 重算所有联盟技能加成 固定值和百分比  加入或者清空
     * @param userId
     * @param pbUserData
     */
    public  static void  rePartnerSkillAddBySkill(long userId, PBUserData.Builder pbUserData){
        // 增量更新 等级带来的战力加成
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserPower userPower = GameUser.getUserPower(userId);
        String powerAddUnionNew = getPowerAddUnionNew(userId);
        String powerAddUnionNewCv = getPowerAddUnionNewCv(userId);
        userPower.putPowerAddUnionCv(powerAddUnionNewCv);
        userPower.putPowerAddUnionPer(powerAddUnionNew);
        List<UserPartner> partnerList =  userPower.takeUserPartnerList(0);  // 所有的干员 都需要重算
        PartnerManager.batchUpdatePartnerPower(pbUserData, userInfo, userPower, partnerList);
    }



    /**
     * 添加联盟技能加成 固定值
     * @param userId
     * @param pbUserData
     * @param decoration
     * @param unionUnlockDecoration
     */
    public  static boolean  addPartnerSkillAddBySkillNew(long userId, PBUserData.Builder pbUserData, UnionDecoration decoration,UnionUnlockDecoration unionUnlockDecoration){
        // 增量更新 等级带来的战力加成
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserPower userPower = GameUser.getUserPower(userId);
        Skill decorationSkill = SkillManager.getSkill(decoration.getSkill());
        int effectParam = decorationSkill.getEffectParam();
        int addValue = decorationSkill.takeLevelUpDiff(unionUnlockDecoration.getLevel()); // 增量
        JsonArray objects = SkillManager.addSkillEffectArray(effectParam, addValue, userPower.getPowerAddUnionCvArray());
        boolean isChange = !userPower.getPowerAddUnionCv().equals(objects.toString());
        userPower.putPowerAddUnionCv(objects.toString());
        List<UserPartner> partnerList =  userPower.takeUserPartnerList(decorationSkill.getEffectParam());  // 对应性格的干员
        PartnerManager.batchUpdatePartnerPower(pbUserData, userInfo, userPower, partnerList);
        return isChange;
    }


    /**
     * 添加联盟技能加成  百分比
     * @param userId
     * @param pbUserData
     */
    public  static boolean  addPartnerSkillAddBySkillNewPer(long userId,long unionId, PBUserData.Builder pbUserData){
        boolean isChange = false;
        // 增量更新 等级带来的战力加成
        List<UnionUnlockDecoration> unionUnlockDecorationList = getUnionUnlockDecorationList(unionId);
        int totalLevel = 0;
        for (UnionUnlockDecoration unlockDecoration:unionUnlockDecorationList){
            totalLevel += unlockDecoration.getLevel();
        }
        int oldLevel = totalLevel - 1;
        for (UnionDecorationEffect decorationEffect : getUnionDecorationEffectList()) {
           if (totalLevel < decorationEffect.getLevel()) {break;}   // 后面技能等级都不满足直接退出
           if (oldLevel > decorationEffect.getLevel()) {continue;}  // 之前的等级的技能过滤
           if (totalLevel == decorationEffect.getLevel()){
               UserPower userPower = GameUser.getUserPower(userId);
               UserInfo userInfo = GameUser.getUserInfo(userId);
               Skill decorationSkill = SkillManager.getSkill(decorationEffect.getEffect());
               int charType = decorationSkill.getEffectParam();
               int addValue = decorationSkill.takeLevelUpDiff(1); // 增量
               JsonArray jsonArray = SkillManager.addSkillEffectArray(charType,addValue, userPower.getPowerAddUnionPerArray());
               userPower.putPowerAddUnionPer(jsonArray.toString());
               isChange = !userPower.getPowerAddUnionPer().equals(jsonArray.toString());
               List<UserPartner> partnerList = userPower.takeUserPartnerList(charType);
               PartnerManager.batchUpdatePartnerPower(pbUserData, userInfo, userPower, partnerList);
               break;
           }
        }
        return isChange;
    }


    /**
     * 重置联盟技能加成, 重算所有干员的战力，和所有商业建筑的收益
     * @param userInfo
     * @param pbUserData
     */
    public static void resetPartnerSkillAddByUserId(UserInfo userInfo, PBUserData.Builder pbUserData) {
        long userId = userInfo.getId();
        UserPower userPower = GameUser.getUserPower(userId);
        String str = SkillManager.createSkillEffectArray().toString();
        userPower.putPowerAddUnionPer(str);
        userPower.putPowerAddUnionCv(str);
        userPower.putEarnAddUnionPer(str);

        List<UserPartner> partnerList = PartnerManager.getUserPartnerList(userInfo.getId());
        PartnerManager.batchUpdatePartnerPower(pbUserData, userInfo, userPower, partnerList);
    }


    /**
     * 加入联盟时，给成员的英雄加上联盟技能加成
     * @param unionId
     * @param userId
     * @param pbUserData
     */
    public static void joinUnionAddPartnerSkillAdd(long unionId, long userId, PBUserData.Builder pbUserData) {
//        List<UnionUnlockDecoration> unionUnlockDecorationList = UnionManager.getUnionUnlockDecorationList(unionId);
//        Map<Integer, Integer> unionDecorationMap = new HashMap<>();
//        int extraValue = 0;
//        for (int i = 0; i < unionUnlockDecorationList.size(); i++) {
//            int skillId = AllParam.UNION_DECORATION_ADD_SKILL_IDS[i];
//            Skill skill = SkillManager.getSkill(skillId);
//            int effectParam = skill.getEffectParam();
//            if (effectParam == 0) { // 0 是给所有属性都加
//                extraValue += skill.getBaseValue();
//                continue;
//            }
//
//            int value = unionDecorationMap.getOrDefault(skill.getEffectParam(), 0);
//            unionDecorationMap.put(skill.getEffectParam(), value + skill.getBaseValue());
//        }
//
//        for (Map.Entry<Integer, Integer> entry : unionDecorationMap.entrySet()) {
//            UnionManager.addPartnerSkillAddBySkill(userId, pbUserData, entry.getKey(),  entry.getValue() + extraValue);
//        }
        rePartnerSkillAddBySkill(userId,pbUserData);  // 加入联盟时需要重算加成战力
    }

    /**
     * 联盟地标对战力的加成信息列表
     * @return jsonarray格式的字符串，固定6个值CHARACTER_TYPE_SIZE + 1，第一个表示所有性格，第二个表示性格1
     */
    public static String getPowerAddUnion(long userId) {
//        UserUnion userUnion = UnionManager.getUserUnion(userId);
//        if (userUnion == null || userUnion.getUnionId() == 0) {
//            return "";
//        }
//        int decorationNum = countUnionDecorationNum(userUnion.getUnionId());// 已经解锁的联盟地标数量
//        if (decorationNum == 0) {
//            return "";
//        }
//
//        JsonArray jsonArray = SkillManager.createSkillEffectArray();
//        for (int i = 0; i < decorationNum; i++) {
//            int skillId = AllParam.UNION_DECORATION_ADD_SKILL_IDS[i];// 已解锁的技能id
//            Skill skill = SkillManager.getSkill(skillId);
//            int index = skill.getEffectParam();//0-5, 0表示全部
//            int newValue = jsonArray.getInteger(index) + skill.getBaseValue();
//            jsonArray.set(index, newValue);
//        }
        return "";
    }

    /**
     * 构建联盟互助列表协议信息（全部）
     * @param unionReciprocityList
     * @return
     */
    public static Common.PBUnionReciprocityList.Builder takePBUnionReciprocityListInitBuilder(boolean isHelp, UnionReciprocityList unionReciprocityList) {
        Common.PBUnionReciprocityList.Builder builder = Common.PBUnionReciprocityList.newBuilder();
        builder.setId(unionReciprocityList.getId());
        builder.setType(unionReciprocityList.getType());
        builder.setHelpNum(unionReciprocityList.getHelpNum());
        builder.setHelpNumMax(unionReciprocityList.getHelpNumMax());
        builder.setIsHelp(isHelp);

        UserShow userShow = GameUser.getUserShow(unionReciprocityList.getUserId());
        builder.setUserShow(userShow.takeInitBuilder());
        return builder;
    }

    /**
     * 构建联盟互助列表协议信息（部分）
     * @param isHelp
     * @param helpNum
     * @return
     */
    public static Common.PBUnionReciprocityList.Builder takePBUnionReciprocityListBuilder(boolean isHelp, int helpNum) {
        Common.PBUnionReciprocityList.Builder builder = Common.PBUnionReciprocityList.newBuilder();
        builder.setHelpNum(helpNum);
        builder.setIsHelp(isHelp);
        return builder;
    }

    // 生成帮助记录
    public static void addUserUnionReciprocityRecord(long userId, UnionReciprocityList unionReciprocityList) {
        UserUnionReciprocityRecord userUnionReciprocityRecord = new UserUnionReciprocityRecord(userId, unionReciprocityList.getId(), unionReciprocityList.getActivateTime());
        userUnionReciprocityRecord.doCreate();
    }

    /**
     * 创建联盟互助的请求信息
     * @param unionId
     * @param userId
     * @param type 1-大世界行军； 2-大世界资源事件；3-医院治疗
     * @param seekId 求助类型对应的ID值
     * @return
     */
    public static UnionReciprocityList createUnionReciprocityList(UnionInfo unionInfo, long userId, int type, long seekId, String uniqeId) {
        int helpNumMax = UnionManager.getReciprocityHelpNumMax(userId, unionInfo);
        UnionReciprocityList unionReciprocityList = new UnionReciprocityList(unionInfo.getId(), userId, type, seekId, uniqeId, helpNumMax);
        unionReciprocityList.doCreate();
        return unionReciprocityList;
    }

    /**
     * 对联盟互助请求，进行帮助
     * @param unionReciprocityList 求助信息
     * @param userInfo 实施帮助的人
     */
    public static void handleDoHelp(PBUserData.Builder pbUserData, UserInfo userInfo, UnionInfo unionInfo, UnionReciprocityList unionReciprocityList) {
        long userIdTarget = unionReciprocityList.getUserId();// 发起人的userid
        int type = unionReciprocityList.getType();
        UnionMain unionMain = getUnionMain(unionInfo.getLevel());
        if (unionMain == null || unionMain.getHelpTime() == 0) {
            return;
        }
        unionReciprocityList.addHelpNum(1);// 增加被帮助的次数
        switch (type) {
            case UnionConstant.UNION_RECIPROCITY_TYPE_1 :
            case UnionConstant.UNION_RECIPROCITY_TYPE_2 : {
                // 对行军进行助力，增加扣除的时间，并推送给发起求助的玩家
                Lock lock = null;
                try {
                    lock = MainService.getVertLock(LockKey.getWorldTeam(userIdTarget));
                    WorldManager.handleDoHelp(userIdTarget, (int)unionReciprocityList.getSeekId(), unionReciprocityList.getUniqeId(), unionMain.getHelpTime(), userInfo, unionReciprocityList);
                } catch (Exception e) {
                    return;
                } finally {// 释放锁
                    MainService.releaseVertLock(lock);
                }
                break;
            }
            case UnionConstant.UNION_RECIPROCITY_TYPE_3 : {
                BuildManager.handleDoHelp(userIdTarget, unionReciprocityList.getUniqeId(), unionMain.getHelpTime(), userInfo, unionReciprocityList);
                break;
            }
        }
    }

    /**
     * 获取联盟互助可帮助次数（这里不校验每条数据还能真正可帮助）
     * @param userId
     * @param unionId
     * @return
     */
    public static int countHelpNum(long userId, long unionId, UnionInfo unionInfo) {
        List<UnionReciprocityList> allUnionReciprocityList = getUnionReciprocityList(unionInfo.getId());
        if (allUnionReciprocityList.isEmpty()) {
            return 0;
        }

        List<UserUnionReciprocityRecord> recordList = UnionManager.getUserUnionReciprocityRecordList(userId);// 帮助记录
        int count = 0;
        for (UnionReciprocityList unionReciprocityList : allUnionReciprocityList) {
            if (unionReciprocityList.isCanHelp(userId, recordList, unionInfo)) {
                count++;
            }
        }
        return count;
    }

    /**
     * 判断用户是否是联盟成员
     * @param userId
     * @return
     */
    public static boolean isUnionMember (long userId) {
        UserUnion userUnion = getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return false;
        }

        long unionId = userUnion.getUnionId();
        UnionInfo unionInfo = getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return false;
        }

        return true;
    }

    /**
     * 判断用户是否是联盟成员
     * @param userId
     * @param unionId
     * @return
     */
    public static boolean isUnionMember (long userId, long unionId) {
        UserUnion userUnion = getUserUnion(userId);
        // 没有加入联盟
        if (userUnion.getUnionId() == 0) {
            return false;
        }
        // 不是这个联盟的
        if (unionId != userUnion.getUnionId()) {
            return false;
        }
        UnionInfo unionInfo = getUnionInfo(unionId);
        // 没有该联盟
        if (unionInfo == null) {
            return false;
        }

        return true;
    }

    /**
     * 删除用户在联盟的所有互助信息
     * 1. 删除用户的互助记录
     * 2. 删除用户的求助记录
     * @param userId
     * @param unionId
     */
    public static void deleteUnionHelpByUserId(long userId, long unionId) {
        List<UserUnionReciprocityRecord> recordList = getUserUnionReciprocityRecordList(userId);
        for (UserUnionReciprocityRecord record : recordList) { // 删除所有帮助记录（可不删除，下次时间超时也会被删除）
            if (record.getUserId() == userId) {
                record.delete();
            }
        }

        List<UnionReciprocityList> allUnionReciprocityList = getUnionReciprocityList(unionId);
        for (UnionReciprocityList unionReciprocityList : allUnionReciprocityList) { // 删除所有求助记录
            if (unionReciprocityList.getUserId() == userId) {
                unionReciprocityList.delete();
            }
        }
    }

    //  联盟地标的数量
    public static int countUnionDecorationNum(long unionId) {
        long num = EntityManager.getEntityCount(UnionUnlockDecoration.class, unionId);
        return (int) num;
    }

    // 该玩家求助信息能被帮助的次数上限
    public static int getReciprocityHelpNumMax(long userId, UnionInfo unionInfo) {
        UnionMain unionMain = UnionManager.getUnionMain(unionInfo.getLevel());
        if (unionMain == null) {
            return 0;
        }
        int addValue = IapManager.takePrivilegeValueByType(userId, PrivilegeCardConstant.TYPE_UNION_HELP_NUM);//特权卡增加的上限次数
        return unionMain.getHelpNum() + addValue;
    }

    /**
     *联盟建筑对建筑的收益的加成
     * @return jsonarray格式的字符串，固定6个值CHARACTER_TYPE_SIZE + 1，第一个表示所有性格，第二个表示性格1
     */
    public static String getEarnAddUnion(long userId) {
        JsonArray jsonArray = SkillManager.createSkillEffectArray();
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (userUnion == null || userUnion.getUnionId() == 0) {
            return jsonArray.toString();// 未加入联盟
        }

        int value0 = 0;
        int value1 = 0;
        int value2 = 0;
        int value3 = 0;
        int value4 = 0;
        int value5 = 0;
        List<UnionBuild> list = getUnionBuildList(userUnion.getUnionId());// 联盟建筑的id
        for (UnionBuild unionBuild : list) {
            if (!unionBuild.isBuildComplete()) {
                continue;// 未建造完成
            }
            int charType = unionBuild.takeEarnAddEffectType();// 对哪个性格的建筑有加成
            int addValue = unionBuild.takeEarnAddEffectValue();// 加成值
            if (addValue == 0) {
                continue;
            }
            if (charType == 0) {// 该技能加成在哪个性格的干员
                value0 += addValue;
            } else if (charType == Constant.CHARACTER_TYPE_1) {
                value1 += addValue;
            } else if (charType == Constant.CHARACTER_TYPE_2) {
                value2 += addValue;
            } else if (charType == Constant.CHARACTER_TYPE_3) {
                value3 += addValue;
            } else if (charType == Constant.CHARACTER_TYPE_4) {
                value4 += addValue;
            } else if (charType == Constant.CHARACTER_TYPE_5) {
                value5 += addValue;
            }
        }
        jsonArray.set(0, value0);
        jsonArray.set(Constant.CHARACTER_TYPE_1, value1);
        jsonArray.set(Constant.CHARACTER_TYPE_2, value2);
        jsonArray.set(Constant.CHARACTER_TYPE_3, value3);
        jsonArray.set(Constant.CHARACTER_TYPE_4, value4);
        jsonArray.set(Constant.CHARACTER_TYPE_5, value5);

        return jsonArray.toString();
    }



    /**
     *联盟建筑对干员的战力的加成 (百分比)
     * @return jsonarray格式的字符串，固定6个值CHARACTER_TYPE_SIZE + 1，第一个表示所有性格，第二个表示性格1
     */
    public static String getPowerAddUnionNew(long userId){
        JsonArray jsonArray = SkillManager.createSkillEffectArray();
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (userUnion == null || userUnion.getUnionId() == 0) {
            return jsonArray.toString();// 未加入联盟
        }
        List<UnionUnlockDecoration> decorations = getUnionUnlockDecorationList(userUnion.getUnionId());
        if (decorations.isEmpty()){
            return jsonArray.toString();// 未解锁地标建筑
        }
        int value0 = 0;
        int value1 = 0;
        int value2 = 0;
        int value3 = 0;
        int value4 = 0;
        int value5 = 0;

        int totalLevel = 0;
        for (UnionUnlockDecoration unlockDecoration : decorations) {
            totalLevel += unlockDecoration.getLevel();
        }

        // 联盟地标建筑总等级加成(百分比)
        CopyOnWriteArrayList<UnionDecorationEffect> effectList = getUnionDecorationEffectList();
        for (UnionDecorationEffect effect : effectList) {
            if (totalLevel < effect.getLevel()) {
                break;
            }
            // 计算获得的技能
            int skillId = effect.getEffect();
            Skill skill = SkillManager.getSkill(skillId);
            int addValue = skill.countTotalAdd(1);
            if (skill.getEffectParam() == 0) {// 该技能加成在哪个性格的干员。配置在effectparam
                value0 += addValue;
            } else if (skill.getEffectParam() == Constant.CHARACTER_TYPE_1) {
                value1 += addValue;
            } else if (skill.getEffectParam() == Constant.CHARACTER_TYPE_2) {
                value2 += addValue;
            } else if (skill.getEffectParam() == Constant.CHARACTER_TYPE_3) {
                value3 += addValue;
            } else if (skill.getEffectParam() == Constant.CHARACTER_TYPE_4) {
                value4 += addValue;
            } else if (skill.getEffectParam() == Constant.CHARACTER_TYPE_5) {
                value5 += addValue;
            }
        }


        jsonArray.set(0, value0);
        jsonArray.set(Constant.CHARACTER_TYPE_1, value1);
        jsonArray.set(Constant.CHARACTER_TYPE_2, value2);
        jsonArray.set(Constant.CHARACTER_TYPE_3, value3);
        jsonArray.set(Constant.CHARACTER_TYPE_4, value4);
        jsonArray.set(Constant.CHARACTER_TYPE_5, value5);
        return jsonArray.toString();
    }

    // 联盟 固定值加成
    public static String getPowerAddUnionNewCv(long userId){
        JsonArray jsonArray = SkillManager.createSkillEffectArray();
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (userUnion == null || userUnion.getUnionId() == 0) {
            return jsonArray.toString();// 未加入联盟
        }
        List<UnionUnlockDecoration> decorations = getUnionUnlockDecorationList(userUnion.getUnionId());
        if (decorations.isEmpty()){
            return jsonArray.toString();// 未解锁地标建筑
        }
        int value0 = 0;
        int value1 = 0;
        int value2 = 0;
        int value3 = 0;
        int value4 = 0;
        int value5 = 0;
        for (UnionUnlockDecoration unlockDecoration : decorations) {
            UnionDecoration unionDecoration = getUnionDecoration((int) unlockDecoration.getId());
            if (unionDecoration == null || unionDecoration.getSkill() == 0) {
                continue;
            }
            Skill skill = SkillManager.getSkill(unionDecoration.getSkill());
            int addValue = skill.countTotalAdd(unlockDecoration.getLevel());

            if (skill.getEffectParam() == 0) {// 该技能加成在哪个性格的干员。配置在effectparam
                value0 += addValue;
            } else if (skill.getEffectParam() == Constant.CHARACTER_TYPE_1) {
                value1 += addValue;
            } else if (skill.getEffectParam() == Constant.CHARACTER_TYPE_2) {
                value2 += addValue;
            } else if (skill.getEffectParam() == Constant.CHARACTER_TYPE_3) {
                value3 += addValue;
            } else if (skill.getEffectParam() == Constant.CHARACTER_TYPE_4) {
                value4 += addValue;
            } else if (skill.getEffectParam() == Constant.CHARACTER_TYPE_5) {
                value5 += addValue;
            }
        }
        jsonArray.set(0, value0);
        jsonArray.set(Constant.CHARACTER_TYPE_1, value1);
        jsonArray.set(Constant.CHARACTER_TYPE_2, value2);
        jsonArray.set(Constant.CHARACTER_TYPE_3, value3);
        jsonArray.set(Constant.CHARACTER_TYPE_4, value4);
        jsonArray.set(Constant.CHARACTER_TYPE_5, value5);
        return jsonArray.toString();
    }

    public static UnionDynamicRecord addUnionDynamicRecord(long unionId, int msgSystemwordId,Object... params) {
        String msg = MailManager.makeWordIdString(MailConstant.MAIL_ID_TYPE_SYSTEM, msgSystemwordId);
        String msgReplace = "";
        if (params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                String ss = String.valueOf(params[i]);
                if (!Tool.isEmpty(ss)) {
                    msgReplace += params[i];
                }
                if (i < params.length - 1) {
                    msgReplace += "|";
                }
            }
        }
        UnionDynamicRecord unionDynamicRecord = new UnionDynamicRecord(unionId, msg, msgReplace);
        unionDynamicRecord.doCreate();
        return unionDynamicRecord;
    }
}
